package com.ymttest.business.service.YMTTrading;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.common.collect.Lists;
import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.OrderSourceEnum;
import com.ymatou.iapi.optrade.parameter.req.PlaceOrderReq;
import com.ymatou.iapi.optrade.parameter.vo.CouponVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderGroupVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderItemVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderVo;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.productmanager.parameter.UpdateProductCatalogDto;
import com.ymatou.iapi.productmanager.parameter.UpdateProductCatalogsBean;
import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymatou.iapi.productmanager.service.UpdateProductCatalogsCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.ProductManagerCallServiceV2;
import com.ymttest.database.model.YmtCatalogsI;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.utils.EnvSetup;

public class TradingPlaceHunterOrderCallService {
	
	/**
	 * 生成分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单）
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOrder(long hunterId,
			int hunterOrderType) throws Exception {

		return placeHunterOrder(hunterId, 100, 0, hunterOrderType, false, false);
	}

	/**
	 * 生成分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单）
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOrder(long hunterId,
			long userId, int hunterOrderType) throws Exception {

		return placeHunterOrder(hunterId, 100, userId, hunterOrderType, false, false);
	}
	
	/**
	 * 生成分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单） 
	 * @param useCoupon 是否使用优惠券
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOrder(long hunterId, int num,
			long userId, int hunterOrderType, boolean userCoupon) throws Exception {

		return placeHunterOrder(hunterId, num, userId, hunterOrderType, userCoupon, false);
	}

	/**
	 * 生成分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单）
	 * @param num
	 *            购买数量
	 * @param useCoupon
	 * 		       是否使用优惠券
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static TradingServiceResp placeHunterOrder(long hunterId, int num,
			long userId, int hunterOrderType, boolean useCoupon, boolean zeroCommission) throws Exception {

		long sellerId = 20336378;
		String sellerName = "fyftest1";

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq();
		
		OrderGroupVo orderGroupVo = TradingCallService.createOrderGroupVo(sellerId, sellerName);
		OrderVo orderVo = TradingCallService.createOrderVo();

		if (userId == 0)
			placeOrderReq
					.withUserId(Long.valueOf(EnvSetup.getData("BuyUserId")));
		else
			placeOrderReq.withUserId(userId);

		placeOrderReq.setHunterId(String.valueOf(hunterId));
		placeOrderReq.setHunterOrderType(String.valueOf(hunterOrderType));
		placeOrderReq.setOrderSource(OrderSourceEnum.HunterMP);
		placeOrderReq.setBizSource(null);

		if (hunterOrderType == 1) {
			AddSellerProductRequest addSellerProductBean = ProductManagerCallServiceV2
					.initAddSellerGlobalPspProductRequest((int)sellerId);
			
			String productId = ProductManagerCallServiceV2
					.addNewProduct(addSellerProductBean).get("Data")
					.getAsJsonObject().get("ProductId").getAsString();
			ProductManagerCallServiceV2.AddSellerGlobalPspProduct((int)sellerId, productId, 1);
			List<YmtCatalogsI> catalogslist = new YmtCatalogsIWapper()
					.selectCatalogsByProductId(productId);
			String catalogId = catalogslist.get(0).getsCatalogId();
			OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
					productId, catalogId);
			
			List<BigDecimal> saleCommissionList = new ArrayList<>();
			
			if (zeroCommission) {
				
				saleCommissionList.add(BigDecimal.ZERO);
				saleCommissionList.add(BigDecimal.ZERO);
				saleCommissionList.add(BigDecimal.ZERO);
				saleCommissionList.add(BigDecimal.ZERO);
			} else {
				
				saleCommissionList.add(new BigDecimal("0.1"));
				saleCommissionList.add(new BigDecimal("0.3"));
				saleCommissionList.add(new BigDecimal("0.5"));
				saleCommissionList.add(new BigDecimal("0.7"));
			}

			ProductManagerCallServiceV2.UpdateCatalogCommisionsV2((int)sellerId,
					productId, catalogId, sellerName, saleCommissionList);
			ProductManagerCallServiceV2.UpdateProductCommision((int)sellerId,
					productId, sellerName, new BigDecimal(0.25));

			orderItemVo.setProductNum(num);
			orderVo.setOrderItems(Lists.newArrayList(orderItemVo));

		} else {
			AddSellerProductRequest addSellerProductBean = ProductManagerCallServiceV2
					.initAddSellerGlobalPspProductRequest((int)sellerId);
			String productId = ProductManagerCallServiceV2
					.addNewProduct(addSellerProductBean).get("Data")
					.getAsJsonObject().get("ProductId").getAsString();
			List<YmtCatalogsI> catalogslist = new YmtCatalogsIWapper()
					.selectCatalogsByProductId(productId);
			String catalogId = catalogslist.get(0).getsCatalogId();
			
			OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
					productId, catalogId);

			ProductManagerCallServiceV2.UpdateCatalogCommisions((int)sellerId,
					productId, catalogId, sellerName, new BigDecimal("0.6"));
			ProductManagerCallServiceV2.UpdateProductCommision((int)sellerId,
					productId, sellerName, new BigDecimal(0.25));

			orderItemVo.setFreight(BigDecimal.ZERO);
			orderVo.setOrderItems(Lists.newArrayList(orderItemVo));
		}
		
		orderVo.withLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);
		
		if(useCoupon) {
			
			// 使用买手优惠券
			CouponVo sellerCoupon1 = TradingAllPromotion.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);
	
			orderGroupVo.setSellerCoupon(sellerCoupon1);
			
			// 使用平台优惠券
			CouponVo ymatouCoupon = TradingAllPromotion.createYMTCouponVo(userId,
					new BigDecimal(60), BigDecimal.TEN);
			placeOrderReq.setYmatouCoupon(ymatouCoupon);
		}
		
		orderGroupVo.setOrders(Arrays.asList(orderVo));
		placeOrderReq.setOrderGroups(Arrays.asList(orderGroupVo));
		
		TradingServiceResp resp = TradingCallService
				.callPlaceOrderService(placeOrderReq);

		return resp;
	}
	
	/**
	 * 生成特殊大礼包分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param hunterOrderType
	 *            推手订单类型（1：大礼包订单，2：普通订单）
	 * @param num
	 *            购买数量
	 * @param useCoupon
	 * 		       是否使用优惠券
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static TradingServiceResp placeSpecialGiftBagHunterOrder(long hunterId, int num,
			long userId, boolean useCoupon, boolean zeroCommission) throws Exception {

		long sellerId = 20336378;
		String sellerName = "fyftest1";
		
		String productId = "p2148963";
		String catalogId = "c3702475";

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq();
		
		OrderGroupVo orderGroupVo = TradingCallService.createOrderGroupVo(sellerId, sellerName);
		OrderVo orderVo = TradingCallService.createOrderVo();

		if (userId == 0)
			placeOrderReq
					.setUserId(Long.valueOf(EnvSetup.getData("BuyUserId")));
		else
			placeOrderReq.setUserId(userId);

		placeOrderReq.setHunterId(String.valueOf(hunterId));
		placeOrderReq.setHunterOrderType("1");
		placeOrderReq.setOrderSource(OrderSourceEnum.HunterMP);
		placeOrderReq.setBizSource(null);	
		
		updateGiftBagProductNum(productId, (int)sellerId, catalogId);
		
		OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
				productId, catalogId);
		
		List<BigDecimal> saleCommissionList = new ArrayList<>();
		
		if (zeroCommission) {
			
			saleCommissionList.add(BigDecimal.ZERO);
			saleCommissionList.add(BigDecimal.ZERO);
			saleCommissionList.add(BigDecimal.ZERO);
			saleCommissionList.add(BigDecimal.ZERO);
		} else {
			
			saleCommissionList.add(new BigDecimal("0.1"));
			saleCommissionList.add(new BigDecimal("0.3"));
			saleCommissionList.add(new BigDecimal("0.5"));
			saleCommissionList.add(new BigDecimal("0.7"));
		}

		ProductManagerCallServiceV2.UpdateCatalogCommisionsV2((int)sellerId,
				productId, catalogId, sellerName, saleCommissionList);
		ProductManagerCallServiceV2.UpdateProductCommision((int)sellerId,
				productId, sellerName, new BigDecimal(0.25));

		orderItemVo.setProductNum(num);
		orderVo.setOrderItems(Lists.newArrayList(orderItemVo));
		
		orderVo.setLogisticsType(LogisticsTypeEnum.PackageDelivery);
		
		if(useCoupon) {
			
			// 使用买手优惠券
			CouponVo sellerCoupon1 = TradingAllPromotion.createSellerCouponVo(
					userId, sellerId, new BigDecimal(30), BigDecimal.TEN);
	
			orderGroupVo.setSellerCoupon(sellerCoupon1);
			
			// 使用平台优惠券
			CouponVo ymatouCoupon = TradingAllPromotion.createYMTCouponVo(userId,
					new BigDecimal(60), BigDecimal.TEN);
			placeOrderReq.setYmatouCoupon(ymatouCoupon);
		}
		
		orderGroupVo.setOrders(Arrays.asList(orderVo));
		placeOrderReq.setOrderGroups(Arrays.asList(orderGroupVo));
		
		TradingServiceResp resp = TradingCallService
				.callPlaceOrderService(placeOrderReq);

		return resp;
	}
	
	/**
	 * 生成优选团商品分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param num
	 *            购买数量
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOptimizedOrder(long hunterId,
			int num, long userId) throws Exception {
		return placeHunterOptimizedOrder(hunterId, num, userId, false, false);
	}
	
	/**
	 * 生成优选团商品分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param num
	 *            购买数量
	 * @return
	 * @throws Exception
	 */
	public static TradingServiceResp placeHunterOptimizedOrder(long hunterId,
			int num, long userId, boolean mixProduct) throws Exception {
		return placeHunterOptimizedOrder(hunterId, num, userId, mixProduct, false);
	}
	
	/**
	 * 生成优选团商品分销订单
	 * 
	 * @param hunterId
	 *            推手id
	 * @param userId
	 *            用户id
	 * @param num
	 *            购买数量
	 *            
	 * @param mixProduct 是否添加一个普通商品
	 * @param zeroCommission 是否0佣金
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static TradingServiceResp placeHunterOptimizedOrder(long hunterId, int num,
			long userId, boolean mixProduct, boolean zeroCommission) throws Exception {

		int sellerId = 20336378;
		String sellerName = "fyftest1";

		PlaceOrderReq placeOrderReq = TradingCallService
				.buildStandPlaceOrderReq();
		
		OrderGroupVo orderGroupVo = TradingCallService.createOrderGroupVo(sellerId, sellerName);
		OrderVo orderVo = TradingCallService.createOrderVo();

		if (userId == 0)
			placeOrderReq
					.setUserId(Long.valueOf(EnvSetup.getData("BuyUserId")));
		else
			placeOrderReq.setUserId(userId);

		placeOrderReq.setHunterId(String.valueOf(hunterId));
		placeOrderReq.setHunterOrderType("2");
		placeOrderReq.setOrderSource(OrderSourceEnum.HunterMP);
		placeOrderReq.setBizSource(null);

		AddSellerProductRequest addSellerProductBean = ProductManagerCallServiceV2
				.initAddSellerGlobalPspProductRequest(sellerId);

		String productId = ProductManagerCallServiceV2
				.addNewProduct(addSellerProductBean).get("Data")
				.getAsJsonObject().get("ProductId").getAsString();
		ProductManagerCallServiceV2.AddSellerGlobalPspProduct(sellerId,
				productId, 2);
		List<YmtCatalogsI> catalogslist = new YmtCatalogsIWapper()
				.selectCatalogsByProductId(productId);
		String catalogId = catalogslist.get(0).getsCatalogId();
		
		OrderItemVo orderItemVo = TradingCallService.createOrderItemVo(
				productId, catalogId);
		
		ProductManagerCallServiceV2.UpdateCatalogCommisions(sellerId,
				productId, catalogId, sellerName, new BigDecimal("0.6"));
		ProductManagerCallServiceV2.UpdateProductCommision(sellerId,
				productId, sellerName, new BigDecimal(0.25));

		orderItemVo.setProductNum(num);
		orderVo.setOrderItems(Lists.newArrayList(orderItemVo));
		
		//如果混合了普通商品，则添加一个普通商品
		if (mixProduct) {
			
			AddSellerProductRequest addSellerProductBean1 = ProductManagerCallServiceV2
					.initAddSellerGlobalPspProductRequest(sellerId);
			String productId1 = ProductManagerCallServiceV2
					.addNewProduct(addSellerProductBean1).get("Data")
					.getAsJsonObject().get("ProductId").getAsString();
			List<YmtCatalogsI> catalogslist1 = new YmtCatalogsIWapper()
					.selectCatalogsByProductId(productId1);
			String catalogId1 = catalogslist1.get(0).getsCatalogId();
			OrderItemVo orderItemVo1 = TradingCallService.createOrderItemVo(
					productId1, catalogId1);

			ProductManagerCallServiceV2.UpdateCatalogCommisions(sellerId,
					productId1, catalogId1, sellerName, new BigDecimal("0.6"));
			ProductManagerCallServiceV2.UpdateProductCommision(sellerId,
					productId1, sellerName, new BigDecimal(0.25));

			orderItemVo1.setProductNum(num);
			orderVo.getOrderItems().add(orderItemVo1);
		}

		orderVo.setLogisticsType(LogisticsTypeEnum.PackageDelivery);
		
		orderGroupVo.setOrders(Arrays.asList(orderVo));
		placeOrderReq.setOrderGroups(Arrays.asList(orderGroupVo));

		TradingServiceResp resp = TradingCallService
				.callPlaceOrderService(placeOrderReq);

		return resp;
	}
	
	@SuppressWarnings("deprecation")
	public static void updateGiftBagProductNum(String productId, int sellerId, String catalogId) {
		
		UpdateProductCatalogsBean updateProductCatalogsBean = new UpdateProductCatalogsBean();
		UpdateProductCatalogsCall updateProductCatalogsCall = new UpdateProductCatalogsCall();
		
		updateProductCatalogsBean.setProductID(productId);
		updateProductCatalogsBean.setUserID(sellerId);
		UpdateProductCatalogDto updateCatalogDto = new UpdateProductCatalogDto();
		updateCatalogDto.setCatalogId(catalogId);
		updateCatalogDto.setUserId(sellerId);
		updateCatalogDto.setNum(1000000);
		updateCatalogDto.setPrice(Double.valueOf("16.00"));
		updateCatalogDto.setVipPrice(Double.valueOf("12.00"));
		updateCatalogDto.setNewCustomerPrice(Double.valueOf("8.00"));
		updateCatalogDto.setMarketPrice(Double.valueOf("20.00"));
		updateProductCatalogsBean.setCatalogs(Arrays.asList(updateCatalogDto));
		
		JSONObject ret = updateProductCatalogsCall.callAndGetReturnData(updateProductCatalogsBean);
		
		try {
			
			if (ret.getInt("Code") == 200)
				Logger.comment("修改库存成功");
			else
				Logger.comment("修改库存失败");
		} catch(JSONException e) {
			e.printStackTrace();
		}
	}
}
